<template>
  <div class="login">
      <div class="login-box">
        <h3 class="title">设置头像</h3>
          <a-upload
            list-type="picture-card"
            :show-upload-list="false"
            :before-upload="_=>false"
            @change="handleChange"
          >
            <img style="width:80px;" v-if="imageUrl" :src="$http.baseURL+'/public/pic/'+imageUrl" alt="avatar" />
          </a-upload>
          <a-form :wrapperCol="{span: 12}" ref="ruleForm" :model="form" :rules="rules" @finish="handleSubmit">
            <a-form-item name="nickname">
              <a-input
                v-model:value="form.nickname"
                type="text"
                placeholder="请输入昵称"
              >
              <template v-slot:prefix><UserOutlined /></template>
              </a-input>
            </a-form-item>
            <a-form-item name="password">
              <a-input
                v-model:value="form.password"
                placeholder="请输入密码"
              ><template v-slot:prefix><LockOutlined /></template></a-input>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit" :loading="isloading">提交</a-button>
            </a-form-item>
          </a-form>
      </div>
</div>
</template>
<script>
export default {
  data() {
    return {
      imageUrl: '',
      form: {
        nickname: '',
        password: '',
      },
      rules:{
        nickname: [{ required: true, message: '请输入昵称' }],
        password: [{ required: true, message: '请输入密码' }],
      },
      isloading:false
    };
  },
  mounted(){
    this.form.nickname = localStorage.nickname
    this.imageUrl = localStorage.avatar
  },
  methods: {
    handleChange(file){
      var body = new FormData()
      body.append('file',file.file)
      fetch(this.$http.baseURL+'/upload',{method: 'POST',body,headers: { token: localStorage.token||'' }}).then(_=>_.json()).then(_=>{
        this.imageUrl=_.path
      })
    },
    handleSubmit(values) {
      this.isloading=true;
      values.avatar = this.imageUrl
      this.updateFunc(values);
    },
    updateFunc(values){
      this.$http.get("/updateUser",values).then(res => {
        this.isloading=false;
        this.$message.success(`修改成功！`);
        this.$root.nickname = values.nickname
        this.$root.avatar = values.avatar
        localStorage.avatar = values.avatar
        localStorage.nickname = values.nickname
      });
    },
  }
};
</script>

<style scoped>
</style>
